package com.oanda.blackberry.view;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.GIFEncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.decor.BorderFactory;

import com.oanda.blackberry.ui.AnimatedGIFField;
import com.oanda.blackberry.ui.BitmapButtonField;
import com.oanda.blackberry.util.AbstractViewPanel;
import com.oanda.blackberry.util.DefaultController;
import com.oanda.blackberry.util.PropertyChangeEvent;
import com.oanda.blackberry.util.log.Logger;

public class StatusView2 implements AbstractViewPanel {
    Dialog d;
    String title = "";
    String message = "";
    OKDialogListener listener;
    DefaultController controller;
    boolean isDisplayed = false;
    LabelField messageF;

    public StatusView2(DefaultController controller, OKDialogListener listener) {
        this.controller = controller;
        this.listener = listener;
    }

    public void showDialog() {
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public synchronized void run() {
                Object[] choices = new Object[0];
                int[] values = { -1 };
                if (StatusView2.this.d == null) {
                    StatusView2.this.d = new Dialog(StatusView2.this.title, choices, values, 0,
                            null) {
                        boolean escapePressed = false;

                        protected boolean keyChar(char key, int status, int time) {
                            if (key == '\033') {
                                this.escapePressed = true;
                            }

                            return super.keyChar(key, status, time);
                        }

                        protected void onUiEngineAttached(boolean attached) {
                            if (attached) {
                                StatusView2.this.isDisplayed = true;
                            } else {
                                StatusView2.this.isDisplayed = false;
                                if (this.escapePressed) {
                                    if (StatusView2.this.listener != null) {
                                        StatusView2.this.listener.performAction(new Boolean(true));
                                    }
                                    this.escapePressed = false;
                                    return;
                                }
                            }
                        }

                        public void paintBackground(Graphics g) {
                            g.setColor(0);
                            g.setGlobalAlpha(230);
                            g.setDrawingStyle(1, true);
                            g.fillRoundRect(0, 0, Math.max(getContentWidth(), 50),
                                    Math.max(getContentHeight(), 50), 8, 8);
                            g.setColor(16119285);
                        }
                    };
                    StatusView2.this.d.setFont(DefaultController.getComponentFont());
                    StatusView2.this.d.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1,
                            1, 1), 2));

                    StatusView2.this.d.getDelegate().setPadding(12, 12, 12, 12);

                    StatusView2.this.messageF = new LabelField(StatusView2.this.message,
                            12884901888L);
                    StatusView2.this.messageF.setFont(DefaultController.getComponentFont().derive(
                            0, 20));

                    GIFEncodedImage _theImage = (GIFEncodedImage) EncodedImage
                            .getEncodedImageResource("ajax-loader6.bin");
                    try {
                        StatusView2.this.d.getLabel().setFont(Font.getDefault().derive(0, 2));
                    } catch (Throwable t) {
                    }
                    HorizontalFieldManager hM = new HorizontalFieldManager();
                    hM.add(new AnimatedGIFField(_theImage));
                    hM.add(StatusView2.this.messageF);
                    StatusView2.this.d.add(hM);

                    BitmapButtonField b = new BitmapButtonField(Bitmap
                            .getBitmapResource("cancel-button-hover-119x37-p24.png"), Bitmap
                            .getBitmapResource("cancel-button-119x37.png"), "Cancel", 12884967424L);

                    b.setFont(DefaultController.getComponentFont().derive(0, 14));
                    b.setPadding(20, 2, 2, 2);
                    b.setMargin(2, 2, 2, 2);
                    b.setChangeListener(new FieldChangeListener() {
                        public void fieldChanged(Field field, int context) {
                            if (context != -2147483648) {
                                if (StatusView2.this.listener != null)
                                    StatusView2.this.listener.performAction(new Boolean(true));
                                StatusView2.this.closeStatus();
                            }
                        }
                    });
                    StatusView2.this.d.add(b);
                } else {
                    StatusView2.this.messageF.setText(StatusView2.this.message);
                }

                if (!StatusView2.this.isDisplayed) {
                    StatusView2.this.d.invalidate();
                    StatusView2.this.d.doModal();
                }
            }
        });
    }

    public static void showInfoDialog(final String message) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {

            public synchronized void run() {
                Object[] choices = new Object[0];
                int[] values = { -1 };

                Dialog d = new Dialog(message, choices, values, 0, null) {
                    boolean escapePressed = false;

                    protected boolean keyChar(char key, int status, int time) {
                        if (key == '\033')
                            ;
                        return super.keyChar(key, status, time);
                    }

                    protected void onUiEngineAttached(boolean attached) {
                        if (attached)
                            ;
                    }

                    public void paintBackground(Graphics g) {
                        g.setColor(0);
                        g.setGlobalAlpha(230);
                        g.setDrawingStyle(1, true);
                        g.fillRoundRect(0, 0, Math.max(getContentWidth(), 50),
                                Math.max(getContentHeight(), 50), 8, 8);
                        g.setColor(16119285);
                    }
                };
                d.setFont(DefaultController.getComponentFont());
                d.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), 2));

                d.setBackground(BackgroundFactory.createSolidTransparentBackground(255, 240));

                d.getDelegate().setPadding(12, 12, 12, 12);

                BitmapButtonField b = new BitmapButtonField(Bitmap
                        .getBitmapResource("ok-button-hover.png"), Bitmap
                        .getBitmapResource("ok-button-p24.png"), "Cancel", 12884967424L);

                b.setFont(DefaultController.getComponentFont().derive(0, 22));
                b.setChangeListener(new FieldChangeListener() {
                    private Dialog val$d;

                    public void fieldChanged(Field field, int context) {
                        if (context != -2147483648) {
                            this.val$d.close();
                        }
                    }
                });
                d.add(b);
                d.invalidate();
                d.show();
            }
        });
    }

    public static void showInfoDialog(String message, OKDialogListener listener) {
        showInfoDialog(message, listener, true);
    }

    public static void showInfoDialog(final String message, final OKDialogListener listener,
            final boolean neverShowAgain) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {

            public synchronized void run() {
                Object[] choices = new Object[0];
                int[] values = { -1 };

                final CheckboxField checkBox = new CheckboxField("Never show this message again.",
                        false);
                Dialog d = new Dialog(message, choices, values, 0, null) {
                    boolean escapePressed;
                    private CheckboxField checkboxField;

                    protected boolean keyChar(char key, int status, int time) {
                        if (key == '\033') {
                            this.escapePressed = true;
                        }

                        return super.keyChar(key, status, time);
                    }

                    protected void onUiEngineAttached(boolean attached) {
                        if (!attached) {
                            if (this.escapePressed) {
                                if (listener != null) {
                                    listener.performAction(new Boolean(checkboxField.getChecked()));
                                }
                                this.escapePressed = false;
                                return;
                            }
                        }
                    }

                    public void paintBackground(Graphics g) {
                        g.setColor(0);
                        g.setGlobalAlpha(230);
                        g.setDrawingStyle(1, true);
                        g.fillRoundRect(0, 0, Math.max(getContentWidth(), 50),
                                Math.max(getContentHeight(), 50), 8, 8);
                        g.setColor(16119285);
                    }
                };
                d.setFont(DefaultController.getComponentFont());
                d.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), 2));

                d.getDelegate().setPadding(12, 12, 12, 12);

                BitmapButtonField b = new BitmapButtonField(Bitmap
                        .getBitmapResource("ok-button-hover.png"), Bitmap
                        .getBitmapResource("ok-button-p24.png"), "Cancel", 12884967424L);

                b.setFont(DefaultController.getComponentFont().derive(0, 18));
                b.setPadding(10, 0, 0, 0);
                b.setMargin(0, 0, 0, 0);

                b.setChangeListener(new FieldChangeListener() {

                    public void fieldChanged(Field field, int context) {
                        if (context != -2147483648) {
                            if (listener != null) {
                                listener.performAction(new Boolean(checkBox.getChecked()));
                            }
                            // TODO
                            // StatusView2.this.d.close();
                        }
                    }
                });
                if (neverShowAgain) {
                    d.add(checkBox);
                }
                d.add(b);
                b.setFocus();
                d.invalidate();
                d.show();
            }
        });
    }

    public static void showInfoYesNoDialog(final String message, final OKDialogListener listener) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {

            public synchronized void run() {
                Object[] choices = new Object[0];
                int[] values = { -1 };

                final CheckboxField checkBox = new CheckboxField("Do not show this message again.",
                        false);
                Dialog d = new Dialog(message, choices, values, 0, null) {
                    boolean escapePressed;

                    protected boolean keyChar(char key, int status, int time) {
                        if (key == '\033') {
                            this.escapePressed = true;
                        }

                        return super.keyChar(key, status, time);
                    }

                    protected void onUiEngineAttached(boolean attached) {
                        if (!attached) {
                            if (this.escapePressed) {
                                if (listener != null) {
                                    Boolean[] result = { new Boolean(false),
                                            new Boolean(checkBox.getChecked()) };
                                    listener.performAction(result);
                                }

                                this.escapePressed = false;
                                return;
                            }
                        }
                    }

                    public void paintBackground(Graphics g) {
                        g.setColor(0);
                        g.setGlobalAlpha(230);
                        g.setDrawingStyle(1, true);
                        g.fillRoundRect(0, 0, Math.max(getContentWidth(), 50),
                                Math.max(getContentHeight(), 50), 8, 8);
                        g.setColor(16119285);
                    }
                };
                d.setFont(DefaultController.getComponentFont());
                d.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), 2));

                d.getDelegate().setPadding(12, 12, 12, 12);

                BitmapButtonField bYes = new BitmapButtonField(Bitmap
                        .getBitmapResource("yes-button-hover.png"), Bitmap
                        .getBitmapResource("yes-button.png"), "Yes", 12884967424L);

                BitmapButtonField bNo = new BitmapButtonField(Bitmap
                        .getBitmapResource("no-button-hover.png"), Bitmap
                        .getBitmapResource("no-button.png"), "No", 12884967424L);

                bYes.setFont(DefaultController.getComponentFont().derive(0, 18));
                bYes.setPadding(10, 0, 8, 0);
                bYes.setMargin(0, 0, 0, 0);
                bNo.setFont(DefaultController.getComponentFont().derive(0, 18));
                bNo.setPadding(10, 0, 8, 0);
                bNo.setMargin(0, 0, 0, 0);

                bYes.setChangeListener(new FieldChangeListener() {

                    public void fieldChanged(Field field, int context) {
                        if (context != -2147483648) {
                            if (listener != null) {
                                Boolean[] result = { new Boolean(true),
                                        new Boolean(checkBox.getChecked()) };
                                listener.performAction(result);
                            }
                            // TODO
                            // StatusView2.this.d.close();
                        }
                    }
                });
                bNo.setChangeListener(new FieldChangeListener() {

                    public void fieldChanged(Field field, int context) {
                        if (context != -2147483648) {
                            if (listener != null) {
                                Boolean[] result = { new Boolean(false),
                                        new Boolean(checkBox.getChecked()) };
                                listener.performAction(result);
                            }
                            // TODO
                            // StatusView2.this.d.close();
                        }
                    }
                });
                d.add(bYes);
                d.add(bNo);
                d.add(checkBox);
                bYes.setFocus();
                d.invalidate();
                d.show();
            }
        });
    }

    public static void showYesNoDialog(final String message, final OKDialogListener listener) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {

            public synchronized void run() {
                Object[] choices = new Object[0];
                int[] values = { -1 };

                Dialog d = new Dialog(message, choices, values, 0, null) {
                    boolean escapePressed = false;

                    protected boolean keyChar(char key, int status, int time) {
                        if (key == '\033') {
                            this.escapePressed = true;
                        }

                        return super.keyChar(key, status, time);
                    }

                    protected void onUiEngineAttached(boolean attached) {
                        if (!attached) {
                            if (this.escapePressed) {
                                if (listener != null) {
                                    listener.performAction(new Boolean(false));
                                }
                                this.escapePressed = false;
                                return;
                            }
                        }
                    }

                    public void paintBackground(Graphics g) {
                        g.setColor(0);
                        g.setGlobalAlpha(230);
                        g.setDrawingStyle(1, true);
                        g.fillRoundRect(0, 0, Math.max(getContentWidth(), 50),
                                Math.max(getContentHeight(), 50), 8, 8);
                        g.setColor(16119285);
                    }
                };
                d.setFont(DefaultController.getComponentFont());
                d.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), 2));

                d.getDelegate().setPadding(12, 12, 12, 12);

                BitmapButtonField bYes = new BitmapButtonField(Bitmap
                        .getBitmapResource("yes-button-hover.png"), Bitmap
                        .getBitmapResource("yes-button.png"), "Yes", 12884967424L);

                BitmapButtonField bNo = new BitmapButtonField(Bitmap
                        .getBitmapResource("no-button-hover.png"), Bitmap
                        .getBitmapResource("no-button.png"), "No", 12884967424L);

                bYes.setFont(DefaultController.getComponentFont().derive(0, 18));
                bYes.setPadding(10, 0, 2, 0);
                bYes.setMargin(0, 0, 0, 0);
                bNo.setFont(DefaultController.getComponentFont().derive(0, 18));
                bNo.setPadding(2, 0, 2, 0);
                bNo.setMargin(0, 0, 0, 0);

                bYes.setChangeListener(new FieldChangeListener() {

                    public void fieldChanged(Field field, int context) {
                        if (context != -2147483648) {
                            if (listener != null) {
                                listener.performAction(new Boolean(true));
                            }
                            // TODO
                            // StatusView2.this.d.close();
                        }
                    }
                });
                bNo.setChangeListener(new FieldChangeListener() {

                    public void fieldChanged(Field field, int context) {
                        if (context != -2147483648) {
                            if (listener != null) {
                                listener.performAction(new Boolean(false));
                            }
                            // TODO
                            // StatusView2.this.d.close();
                        }
                    }
                });
                d.add(bYes);
                d.add(bNo);
                bYes.setFocus();
                d.invalidate();
                d.show();
            }
        });
    }

    public synchronized void setMessage(String mess) {
        if (mess != null)
            this.message = ("  " + mess);
    }

    public synchronized void setTitle(String mess) {
        this.title = mess;
    }

    public void modelPropertyChange(PropertyChangeEvent evt) {
        Logger.log("StatusView2 " + evt.getPropertyName() + String.valueOf(evt.getNewValue()));
        if (evt.getPropertyName().endsWith("setStatusMessage"))
            setMessage((String) evt.getNewValue());
        else if (evt.getPropertyName().equals("isStatusShown")) {
            if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof Boolean))
                    && (evt.getNewValue().equals(new Boolean(false)))) {
                if (this.d != null) {
                    closeStatus();
                }
            } else if ((this.d != null)
                    && (!UiApplication.getUiApplication().getActiveScreen().equals(this.d))) {
                showDialog();
            } else if (this.d == null)
                showDialog();
        }
    }

    private void closeStatus() {
        UiApplication ui = UiApplication.getUiApplication();
        ui.invokeLater(new Runnable() {
            public void run() {
                StatusView2.this.d.close();
            }
        });
    }
}
